<template>
  <div>
    <div class="task-container">
      <el-form ref="taskForm" :model="taskData" :rules="rules">
      <!-- 任务基本信息 -->
      <div class="data-show">
        <!-- 头部标题 -->
        <div class="data-actions">
          <h3>任务基本信息</h3>
        </div>
        <!-- 内容区 -->
        <div class="data-table">
          <!-- 通用布局行 -->
          <div class="common-row row-between">
            <!-- 配置项 - 平台 -->
            <div class="common-item item-3">
              <label class="condition-label">任务选择</label>
              <el-form-item class="condition-input" prop="system">
                <el-select @change="selectTask" v-model="taskId" clearable placeholder="请选择任务">
                  <el-option v-for="(item, index) in pageData.data" :key="index" :label="item.name" :value="item.id"></el-option>
                  <el-select-loading
                    :hasMore="pageData.hasMore"
                    :page="pageData.page"
                    :loading="pageData.loading"
                    @load-more="pageData.loadingMore"
                  />
                </el-select>
              </el-form-item>
            </div>
          </div>
        </div>
      </div>
      <!-- 任务基本信息 -->
      <div class="data-show">
        <!-- 头部标题 -->
        <div class="data-actions">
          <h3>任务进度信息</h3>
        </div>
        <div class="data-table data-tag-content">
          <!-- 展示 -->
          <div v-if="taskId !== null">
            <!-- 通用布局行 -->
            <div class="common-row row-between">
              <!-- 配置项 - 任务名称 -->
              <div class="common-item item-5">
                <label class="condition-label">任务名称</label>
                <h4 class="condition-input">{{ getContent(taskData.name) }}</h4>
              </div>
              <!-- 配置项 - 任务名称 -->
              <div class="common-item item-5">
                <label class="condition-label">用户</label>
                <h4 class="condition-input">{{ getContent(taskData.infoData.userID) }}</h4>
              </div>
            </div>
            <!-- 通用布局行 -->
            <div class="common-row row-between">
              <!-- 配置项 - 任务名称 -->
              <div class="common-item item-3">
                <label class="condition-label">算法模块</label>
                <h4 class="condition-input">{{ getContent(taskData.infoData.keyType) }}</h4>
              </div>
              <!-- 配置项 - 任务名称 -->
              <div class="common-item item-3">
                <label class="condition-label">参数文件</label>
                <h4 class="condition-input">{{ getContent(taskData.infoData.parameter) }}</h4>
              </div>
              <!-- 配置项 - 任务名称 -->
              <div class="common-item item-3">
                <label class="condition-label">媒体类型</label>
                <h4 class="condition-input">{{ getContent(taskData.infoData.module) }}</h4>
              </div>
            </div>
            <div class="common-row row-between">
              <div class="common-item item-10">
                <label class="condition-label">任务描述</label>
                <h4 class="condition-input">{{ getContent(taskData.description) }}</h4>
              </div>
            </div>
            <div class="common-row row-between" v-if="taskData.infoData.keyOneText">
              <div class="data-show">
                <!-- 标题 -->
                <div class="data-actions data-title-between">
                  <h3>服务器公钥密文</h3>
                </div>
                <div class="data-table data-table-scroll">
                    <p class="text-container">
                      {{ changeJSON(taskData.infoData.keyOneText) }}
                    </p>
                  </div>
              </div>
            </div>
            <div class="common-row row-between" v-if="taskData.infoData.keyTwoText">
              <div class="data-show">
                <!-- 标题 -->
                <div class="data-actions data-title-between">
                  <h3>协商密钥参数密文</h3>
                </div>
                <div class="data-table data-table-scroll">
                    <p class="text-container">
                      {{ changeJSON(taskData.infoData.keyTwoText) }}
                    </p>
                  </div>
              </div>
            </div>
            <div class="common-row row-between" v-if="taskData.infoData.keyTwo">
              <div class="data-show">
                <!-- 标题 -->
                <div class="data-actions data-title-between">
                  <h3>协商密钥参数</h3>
                </div>
                <div class="data-table data-table-scroll">
                    <p class="text-container">
                      {{ taskData.infoData.keyTwo }}
                    </p>
                  </div>
              </div>
            </div>
            <div class="common-row row-between" v-if="taskData.infoData.serverKeyThree">
              <div class="data-show">
                <!-- 标题 -->
                <div class="data-actions data-title-between">
                  <h3>协商密钥</h3>
                </div>
                <div class="data-table data-table-scroll">
                    <p class="text-container">
                      {{ taskData.infoData.serverKeyThree }}
                    </p>
                  </div>
              </div>
            </div>
            <div class="common-row row-between" v-if="taskData.infoData.signature">
              <div class="data-show">
                <!-- 标题 -->
                <div class="data-actions data-title-between">
                  <h3>签名文件</h3>
                </div>
                <div class="data-table data-table-scroll">
                    <p class="text-container">
                      {{ changeJSON(taskData.infoData.signature) }}
                    </p>
                  </div>
              </div>
            </div>
            <div class="common-row row-between" v-if="taskData.infoData.verifyResult">
              <div class="data-show">
                <!-- 标题 -->
                <div class="data-actions data-title-between">
                  <h3>签名认证结果</h3>
                </div>
                <div class="data-table data-table-scroll">
                    <p class="text-container">
                      {{ taskData.infoData.verifyResult }}
                    </p>
                  </div>
              </div>
            </div>
            <div class="common-row row-between" v-if="taskData.infoData.extractingMessageFilePath">
              <div class="data-show">
                <!-- 标题 -->
                <div class="data-actions data-title-between">
                  <h3>消息明文</h3>
                </div>
                <div class="data-table data-table-scroll">
                  <el-image class="file-image" v-if="getModuleShow(taskData.infoData.extractingMessageFilePath, taskData.infoData.module) === '图像'" :src="taskData.infoData.messageFile" fit="contain" :preview-src-list="[taskData.infoData.messageFile]" />
                  <p class="text-container" v-else-if="getModuleShow(taskData.infoData.extractingMessageFilePath, taskData.infoData.module) === '文本'">
                    {{ taskData.infoData.messageFile }}
                  </p>
                  <div class="audio-container audio-show" v-else>
                    <i class="iconfont icon-swticonyinle audio-icon"></i>
                    <p class="audio-filename">{{ taskData.infoData.messageFile }}</p>
                  </div>
                </div>
              </div>
            </div>
          </div>
          <div v-else class="recommend-empty">
            <i class="iconfont icon-wushuju1 data-empty-icon"></i>
            <h3 class="data-empty">暂无数据</h3>
          </div>
        </div>
      </div>
      <!-- 按钮部分 -->
      <div class="btn-groups" v-if="taskData.status >= 3">
        <button type="button" :disabled="taskData.status !== 3" class="btn" v-if="taskData.status === 3" @click="handleSign">签名认证</button>
        <button type="button" :disabled="taskData.status !== 4" class="btn" v-if="taskData.status === 4" @click="handleEnd">消息提取</button>
      </div>
      </el-form>
    </div>
  </div>
</template>
<script setup>
import useAppStore from '@/stores/app';
import { ref, computed, onActivated } from 'vue';
import { useRoute } from 'vue-router';
import { API } from '@/utils/status.js';
import { ElMessage } from 'element-plus';
import * as request from '@/api/steganography';
import * as uploadApi from '@/api/file';
import ElSelectLoading from '@/components/common/ElSelectLoading.vue';

// 假数据
const types = [
  { value: 0, label: '类型1' },
  { value: 1, label: '类型2' }
];

// 表单验证规则
const rules = {};
const defaultObj = {
  id: null,
  name: '',
  description: '',
  system: null,
  type: null,
  // 关键上传属性
  stego: null,
  infoData: {
    userID: null,
    module: null,
    keyType: null,
    parameter: null,
    keyOneText: null,
    keyTwoText: null,
    keyTwo: null,
    serverKeyThree: null,
    signature: null,
    extractingMessageFilePath: null,
    messageFile: null
  }
}

// ============> data <============
const appStore = useAppStore();
const route = useRoute();
// 任务id
const taskId = ref(null);
// 创建任务步骤的表单对象
const taskData = ref({
  id: null,
  name: '',
  description: '',
  system: null,
  type: null,
  // 关键上传属性
  stego: null,
  infoData: {
    userID: null,
    module: null,
    keyType: null,
    parameter: null,
    keyOneText: null,
    keyTwoText: null,
    keyTwo: null,
    serverKeyThree: null,
    signature: null,
    extractingMessageFilePath: null,
    messageFile: null
  }
});
const pageData = ref({
  loading: false,
  hasMore: true,
  name: '',
  status: null,
  // totalCount
  total: 0,
  // pageNo
  page: 1,
  pageSize: 10,
  // totalPage
  pageCount: 5,
  loadingMore(e){
    console.log(e);
    pageData.value.loading = true;
    request.getList({
      pageNo: e,
      pageSize: pageData.value.pageSize,
      moduleType: API.steganography.moduleType.APPTHREE
    })
      .then(res => {
        console.log(res)
        pageData.value.loading = false;
        if (res.list && Array.isArray(res.list)) {
          const datas = res.list.length > 0 ? res.list : [];
          if (e === 1){
            pageData.value.data = [];
          }
          pageData.value.data.push(...datas);
          pageData.value.hasMore = pageData.value.data.length < res.totalCount;
          pageData.value.page = e;
        }
      })
      .catch(err => {
        console.log(err);
        pageData.value.loading = false;
      })
  },
  data: []
});
const getContent = computed(() => {
  return function (content){
    return content ? content : '暂未提供';
  }
})
const changeJSON = computed(() => {
  return function (jsonString){
    return jsonString ? window.decodeURIComponent(JSON.parse(jsonString)) : '';
  }
})
const getModuleShow = computed(() => {
  return function (url, module){
    let fileType = url.slice(url.lastIndexOf('.') + 1);
      let images = ['jpg', 'jpeg', 'png', 'bmp'],
          audios = ['mp3', 'wav', 'flac'],
          txts = ['txt'],
          moduleType;
      if (txts.includes(fileType)) {
        moduleType = '文本'; 
      } else if (images.includes(fileType)){
        moduleType = '图像';
      } else {
        moduleType = '音频';
      }
      return moduleType;
  }
})

// ============> hooks <============
onActivated(() => {
  pageData.value.hasMore = true;
  pageData.value.page = 1;
  pageData.value.data = [];
  getList();
  taskId.value = null;
  taskData.value = JSON.parse(JSON.stringify(defaultObj));
})

// ============> methods <============
function selectTask(e){
  console.log(e);
  console.log(typeof e)
  if (e !== undefined){
    request.getTaskDetailById({id: e})
      .then(res => {
        let result = res;
        result.infoData = JSON.parse(res.infoData);
        console.log(result);
        taskData.value = result;
        if (taskData.value.infoData.extractingMessageFilePath){
          uploadApi.download({filePath: taskData.value.infoData.extractingMessageFilePath})
            .then(res => {
              // console.log(res)
              // let reader = new FileReader();
              // reader.readAsText(res.data, 'UTF-8');
              // reader.onload= function(evt){
              //   taskData.value.messageFile = evt.target.result || ''
              // }
              let moduleType = getModuleShow.value(taskData.value.infoData.extractingMessageFilePath, taskData.value.infoData.module);
              if (moduleType === '图像') {
                taskData.value.infoData.messageFile = window.URL.createObjectURL(res.data);
              } else if (moduleType === '音频'){
                let origin = taskData.value.infoData.extractingMessageFilePath,
                    index;
                if (origin.lastIndexOf('\\') > 0){
                  index = origin.lastIndexOf('\\');
                } else if (origin.lastIndexOf('/') > 0){
                  index = origin.lastIndexOf('/');
                }
                taskData.value.infoData.messageFile = origin.slice(index + 1);
              } else {
                let reader = new FileReader();
                reader.readAsText(res.data, 'UTF-8');
                reader.onload= function(evt){
                  taskData.value.infoData.messageFile = evt.target.result || ''
                }
              }
            })
        }
      })
  } else {
    taskId.value = null;
    taskData.value = JSON.parse(JSON.stringify(defaultObj));
  }
}
function getList(){
  request.getList({
    status: pageData.value.status,
    name: pageData.value.name,
    pageNo: pageData.value.page,
    pageSize: pageData.value.pageSize,
    moduleType: API.steganography.moduleType.APPTHREE
  })
    .then(res => {
      console.log(res);
      pageData.value.data = res.list;
      pageData.value.page = res.pageNo;
      pageData.value.total = res.totalCount;
      pageData.value.pageCount = res.totalPage;
      pageData.value.loading = false;
    })
    .catch(err => {
      console.log(err);
      pageData.value.loading = false;
    })
}
// 签名认证
function handleSign(){
  appStore.openLoading('签名认证中...');
  request.appThreeServerSign({ id: taskId.value })
    .then(res => {
      console.log(res);
      console.log(res.infoData.verifyResult);
      appStore.closeLoading();
      if (res.status === 4 && res.infoData.verifyResult){
        ElMessage.success('签名认证成功');
        taskData.value.status = res.status;
        taskData.value.infoData.verifyResult = res.infoData.verifyResult;
      } else {
        ElMessage.error('签名认证失败，请稍后重试或联系管理员');
      }
    })
    .catch(err => {
      console.log(err);
      appStore.closeLoading();
    })
}
// 隐写提取
function handleEnd(){
  appStore.openLoading('消息提取中...');
  request.appThreeServerExtract({ id: taskId.value })
    .then(res => {
      console.log(res);
      appStore.closeLoading();
      if (res.status === 5 && res.infoData.extractingMessageFilePath){
        ElMessage.success('消息提取成功');
        taskData.value.status = res.status;
        taskData.value.infoData.extractingMessageFilePath = res.infoData.extractingMessageFilePath;
        uploadApi.download({filePath: taskData.value.infoData.extractingMessageFilePath})
          .then(res => {
            let moduleType = getModuleShow.value(taskData.value.infoData.extractingMessageFilePath, taskData.value.infoData.module);
            if (moduleType === '图像') {
              taskData.value.infoData.messageFile = window.URL.createObjectURL(res.data);
            } else if (moduleType === '音频'){
              let origin = taskData.value.infoData.extractingMessageFilePath,
                  index;
              if (origin.lastIndexOf('\\') > 0){
                index = origin.lastIndexOf('\\');
              } else if (origin.lastIndexOf('/') > 0){
                index = origin.lastIndexOf('/');
              }
              taskData.value.infoData.messageFile = origin.slice(index + 1);
            } else {
              let reader = new FileReader();
              reader.readAsText(res.data, 'UTF-8');
              reader.onload= function(evt){
                taskData.value.infoData.messageFile = evt.target.result || ''
              }
            }
            // let reader = new FileReader();
            // reader.readAsText(res.data, 'UTF-8');
            // reader.onload= function(evt){
            //   taskData.value.messageFile = evt.target.result || ''
            // }
          })
      } else {
        ElMessage.error('消息提取失败，请稍后重试或联系管理员');
      }
    })
    .catch(err => {
      console.log(err)
      appStore.closeLoading();
    })
}
</script>
<style lang='scss' scoped>
@import '@/assets/styles/mixin.scss';
.row-between {
  justify-content: space-between;
}
.item-3 {
  width: 30%
}
.item-5 {
  width: 49%;
  // height: auto;
  // padding: 50px 0 60px 0;
}
.item-10 {
  width: 100%;
  height: auto;
  padding: 10px 0;
  .condition-label {
    width: 15%;
  }
  .condition-input {
    width: 80%;
  }
}
.upload {
  width: 100%;
  min-height: 120px;
  height: 120px;
  &::v-deep .el-upload {
    @include wh-100;
    // height: 100%!important;
    .el-upload-dragger {
      @include wh-100;
      border-color: var(--color-main);
      padding: 0;
      .upload-empty {
        @include wh-100;
        @include flex-all-center;
        flex-direction: column;
        .upload-icon {
          font-size: 30px;
          color: var(--color-gray-10);
        }
        .upload-des {
          color: var(--color-gray-10);
        }
      }
      .upload-content {
        @include wh-100;
        @include flex-all-center;
        flex-direction: column;
        .upload-icon {
          font-size: 30px;
          color: var(--color-main);
        }
        .upload-des {
          color: var(--color-main);
        }
      }
    }
  }
}
.btn-groups {
  margin-top: 20px;
  text-align: center;
  .btn {
    margin: 0 20px;
  }
}
.data-tag-content {
  min-height: 300px;
  overflow-y: auto;
  @include scrollBar;
}
.recommend-empty {
  width: 100%;
  height: 100%;
  min-height: 300px;
  background-color: var(--color-gray-5);
  @include flex-all-center;
  // 无数据提示语
  .data-empty {
    color: var(--color-main-5);
    font-size: 16px;
  }
  // 无数据图标
  .data-empty-icon {
    color: var(--color-main-5);
    font-size: 32px;
  }
}
.data-table-scroll {
  max-height: 220px;
  height: auto;
  overflow-y: auto;
  @include scrollBar;
  .file-image {
    width: 100%;
    height: 190px;
    background-color: var(--color-gray-2);
    border: 1px solid var(--color-main-border);
    border-radius: 6px;
  }
}
.audio-container {
  width: 100%;
  height: 190px;
  background-color: var(--color-gray-2);
  border: 1px solid var(--color-main-border);
  border-radius: 6px;
  position: relative;
  overflow: hidden;
  @include flex-all-center;
  .audio-icon {
    font-size: 40px;
    font-weight: bolder;
    color: var(--color-main);
  }
  .audio {
    position: absolute;
    bottom: 0;
    left: 50%;
    width: 105%;
    height: 30px;
    transform: translateX(-50%);
  }
}
.audio-show {
  @include flex-all-center;
  flex-direction: column;
}
</style>